package com.zjut.wx.pay.order;

import com.opensymphony.xwork2.ActionSupport;
import com.zjut.an.config.manager.AnConfigManager;
import com.zjut.an.util.system.Status;
import com.zjut.an.util.tools.DateUtil;
import com.zjut.an.util.tools.IPUtils;
import com.zjut.wx.pay.utils.GetWxOrderno;
import com.zjut.zs.pay.dao.ZsPay;
import com.zjut.zs.pay.manager.ZsPayManager;
import com.zjut.zs.user.dao.ZsUser;
import com.zjut.zs.user.manager.ZsUserManager;
import com.zjut.zs.userstatus.dao.ZsUserStatus;
import com.zjut.zs.userstatus.manager.ZsUserStatusManager;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WxPayAction extends ActionSupport implements ServletResponseAware,
		ServletRequestAware {
	private static final long serialVersionUID = -7962415484844112334L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;

	private Map<String, Object> dataMap;

	private ZsPay pay;

	private Integer doId;
	private Integer opId;
	private String donName;
	private Integer total_fee;
	private String no;
	private String message;

	@Resource(name = "DateUtil")
	private DateUtil dateutil;

	@Resource(name = "ZsPayManager")
	private ZsPayManager paymanager;

	@Resource(name = "ZsUserManager")
	private ZsUserManager umanager;	

	@Resource(name = "ZsUserStatusManager")
	private ZsUserStatusManager smanager;
	
	@Resource(name = "AnConfigManager")
	private AnConfigManager anconfig;

	@Resource(name = "Order")
	private Order order;

/*	public static Map<String, Object> UnifiedOrder(UnifiedOrderReqData reqData)
			throws IOException, SAXException, ParserConfigurationException {
		String res = HttpService.doPost(Configure.UNIFIED_ORDER_API, reqData);
		return XMLParser.getMapFromXML(res);
	}*/

	public String wxPay() {
		dataMap = new HashMap<String, Object>();
		ZsUser user = umanager.getData(request.getParameter("usId"));
		String ip = IPUtils.getIpAddr(request);
		try {
			ZsPay pay = paymanager.addData(user, Status.PAY_WX.getStatus());
			WxPayDto payto = new WxPayDto();
			payto.setOrderId(pay.getOutTradeNo());
			payto.setTotalFee(anconfig.getSingleConfigInfoByName("缴费金额"));
			payto.setSpbillCreateIp(ip);
			payto.setNotifyUrl(anconfig.getSingleConfigInfoByName("回调URL"));
			payto.setBody(anconfig.getSingleConfigInfoByName("订单名称"));
			//payto.setOpenId("openid888");
			System.out.println("#### URL="+order.getCodeurl(payto));
			dataMap.put("codeurl", order.getCodeurl(payto));
			dataMap.put("flag", "success");
			
		} catch (Exception e) {
			e.printStackTrace();
			dataMap.put("flag", "faile");
		}
		return SUCCESS;
	}

	public void paySuccess() throws Exception {
		InputStream inStream = request.getInputStream();
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
		outSteam.close();
		inStream.close();
		String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
		Map<String, Object> map = new GetWxOrderno().doXMLParse(result);
		for (Object keyValue : map.keySet()) {
			System.out.println(keyValue + "=" + map.get(keyValue));
		}

		if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
			// TODO 对数据库的操作
			String no = map.get("out_trade_no").toString();
			String total_fee  = map.get("total_fee").toString();
			
			pay = new ZsPay();
			pay.setOutTradeNo(no);//取出该订单号的订单
			List paylist = paymanager.getDataByInstance(1, 1, null, null, pay).getObjects();
			if (paylist.size() > 0) {
				pay = (ZsPay) paylist.get(0);
				if (Status.PAYSTATUS_NULL.getStatus().equals(pay.getPayEnd())) {
					pay.setTransactionId(map.get("transaction_id").toString());
					pay.setTimeEnd(map.get("time_end").toString());
					//pay.setTotalFee(total_fee);
					pay.setPayEnd(Status.PAYSTATUS_YES.getStatus());
					
					ZsUserStatus userstatus = smanager.getDataByUser(umanager.getData(pay.getUsId()));
					userstatus.setPayStatus(Status.PAYSTATUS_YES.getStatus());
					userstatus.setPayTime(map.get("time_end").toString());
					smanager.updateData(userstatus);
					paymanager.updateData(pay);			
					
				}
			}else{
				System.out.println("#### 未找到订单 out_trade_no："+no);
			}
			response.getWriter().write(setXML("SUCCESS", "")); // 告诉微信服务器，我收到信息了，不要在调用回调action了
			System.out.println("-------------" + setXML("SUCCESS", ""));
		}
	}

	public static String setXML(String return_code, String return_msg) {
		return "<xml><return_code><![CDATA[" + return_code
				+ "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";

	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub
		request = arg0;
		session = request.getSession();
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public String getNo() {
		return no;
	}

	public void setNo(String no) {
		this.no = no;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public Integer getTotal_fee() {
		return total_fee;
	}

	public void setTotal_fee(Integer totalFee) {
		total_fee = totalFee;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Integer getDoId() {
		return doId;
	}

	public void setDoId(Integer doId) {
		this.doId = doId;
	}

	public Integer getOpId() {
		return opId;
	}

	public void setOpId(Integer opId) {
		this.opId = opId;
	}

	public String getDonName() {
		return donName;
	}

	public void setDonName(String donName) {
		this.donName = donName;
	}

}